var Ajax = require("./ajax.js")
var Modal = require("./modal.js")
var app = getApp()
class Login{
  static checkLogin(callback){
    let sessionid = wx.getStorageSync("sessionid");
    if (sessionid){
      app.globalData.sessionid = sessionid;
      if (callback) callback();
    } else{
      Login.login(callback);
    } 
  }
  static login(callback){
    wx.login({
      success: (res) => {
        wx.request({
          url: app.serverUrl + "/mesh/login/",
          method: "post",
          header: {
            "content-type": "application/json",
            "sessionid": app.globalData.sessionid
          },
          data: {code: res.code},
          success: function (res) {
            if (res.data.code != 0) {
              Modal.showErr(res.data.msg);
            } else {
              wx.setStorage({
                key: "sessionid",
                data: res.data.session_id
              });
              app.globalData.sessionid = res.data.session_id;
              if (callback) callback();
            }
          }
        });
      },
      fail: res => {
        Login.login();
      }
    })
    
  }
}

module.exports = Login